﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Xml.Linq;
using System.Xml;
using System.Collections.Generic;
using System.Threading;

using SangoBang;

/// <summary>
/// Summary description for EventController
/// </summary>
/// 
namespace SangoBang
{
    public class EventController
    {
        public EventController()
        {
            //
            // TODO: Add constructor logic here
            //
        }
        public string OnReceiveMsg(String msg, String session_guid)
        {
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(msg);
            XmlElement root = doc.DocumentElement;
            string type = root.GetAttribute("type");
            if (type == "newuser")
            {
                Guid guid = Guid.NewGuid();
                string displayName = root.FirstChild.InnerText;
                Player player = new Player(displayName);
                player.Guid = guid.ToString();
                mGameController.addPlayer(player);
                mplayerDict.Add(guid.ToString(), player);
                this.RefreshPlayerList();
                return guid.ToString();
            }
            return "unkown";


        }


        private Dictionary<String, Player> mplayerDict = new Dictionary<String, Player>();
        private void RefreshPlayerList()
        {
            string msg = "<message type=\"playerList\">";
            lock (mGameController.playerList)
            {
                foreach (var player in mGameController.playerList)
                {
                    msg += "<player>" + player.mName + "</player>";
                }
                msg += "</message>";
                foreach (var player in mGameController.playerList)
                {
                    lock (player.MessageQueue)
                    {
                        player.MessageQueue.Enqueue(msg);
                    }
                    player.MessageEvent.Set();
                }
            }
        }
        public string GetMsg(String guid)
        {
            Player player = mplayerDict[guid];
            String msg;
            if (player.MessageQueue.Count == 0)
            {
                player.MessageEvent.WaitOne(20000, false);
            }
            if (player.MessageQueue.Count == 0)
            {
                return "<message type=\"empty\"/>";
            }
            lock (player.MessageQueue)
            {
                msg = player.MessageQueue.Dequeue();
            }
            return msg;

        }
        GameController mGameController = new GameController();

    }
}
